<?php
/**
 * 为链接上的客户每2s端推送一次数据
 */
class Ws{
    const Host = '0.0.0.0';
    const Port = '8082';
    const Document = __DIR__ . '/public';

    protected $ws = null;
    function __construct(){
        $this->ws = new Swoole\Websocket\Server(self::Host, self::Port);
        // 设置静态路由
        $this->ws->set([
            'worker_num' => 2,
            'enable_static_handler' => true, // 静态路由支持
            'document_root' => self::Document // 静态文件根目录
        ]);

        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('close', [$this, 'onClose']);

        $this->ws->start();
    }

    public static function onOpen($ws, $request){
        echo "client {$request->fd} is comming \n";
        $ws->push($request->fd, "hello client:{$request->fd}");
    }

    public function onMessage($ws, $frame){
        echo "<< {$frame->data} \n";
        Swoole\Timer::tick(2000, function () use($ws, $frame){
            echo ">> -2s\n";
            $ws->push($frame->fd, '-2s');
        });
    }
    
    public function onClose($ws, $fd){
        echo "client {$fd} closed \n";
    }
}

new Ws();